package com.syh.jn.scm.domain.upstream.serivce.UpAccountOfPhone;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.util.secret.PasswordUtils;
import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.jn.scm.domain.upstream.entity.system.UpAccount;
import com.syh.jn.scm.domain.upstream.repository.system.UpAccountRepository;
import com.syh.jn.scm.dto.upstream.system.upAccount.UpAccountVo;
import com.syh.jn.scm.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by soci.song on 2018/12/13.
 */
@Service
public class UpAccountOfPhoneDomainService {

    @Autowired
    private UpAccountRepository upAccountRepository;

    /**
     * 批量验证需要绑定的登录账号密码
     * @return AccountId
     */
    public List<Long> verifyAccountPasswords(List<HashMap<String,String>> accounts){
        List<Long> accountIds = new ArrayList<>();
        accounts.forEach(account ->{
            accountIds.add(verifyAccountPassword(account.get("loginAccount"),account.get("password")));
        });
        return accountIds;
    }

    /**
     * 验证需要绑定的登录账号密码
     * @return AccountId
     */
    public Long verifyAccountPassword(String loginAccount, String password){
        ExtAssert.notNull(loginAccount, "loginAccount为空");
        ExtAssert.notNull(password, "密码为空");
        Wrapper wrapper = Wrapper.build();
        wrapper.append(Restrictions.eq("loginAccount", loginAccount));
        UpAccount upAccount = upAccountRepository.getOne(wrapper);
        if (upAccount == null) {
            throw new BusinessException(loginAccount+"绑定失败： 账号不存在");
        }
        if (PasswordUtils.verify(password, upAccount.getLoginPassword())) {
            UpAccountVo upAccountVo = new UpAccountVo();
            ExtBeanUtils.copyProperties(upAccount, upAccountVo);
            return upAccountVo.getId();
        } else {
            throw new BusinessException(loginAccount+"绑定失败： 密码不正确");
        }
    }

    public void clearCorrelation(Long id) {
        Wrapper we = Wrapper.build().append(Restrictions.eq("loginPhoneId",id));
        List<UpAccount> accounts = upAccountRepository.getList(we);
        accounts.forEach(account ->{
            account.untyingLoginPhone();
        });
    }

    public void bindingAccount(Long id, Long accountId) {
        UpAccount account = upAccountRepository.getById(accountId);
        account.bindingLoginPhone(id);
        upAccountRepository.update(account);
    }

    public void untyingAccount(Long id, Long accountId) {
        UpAccount account = upAccountRepository.getById(accountId);
        account.untyingLoginPhone();
        upAccountRepository.update(account);
    }
}
